﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BotvaBot.Processor
{
    public class PeriodQuantityLimitter
    {
        public TimeSpan Period { get; protected set; }
        public int MaxQuantity { get; protected set; }
        public int ReduceFirstTime { get; protected set; }

        public DateTime StartMoment { get; protected set; }
        public int CurrentQuantity { get; protected set; }
        
        public bool IsStarted { get; protected set; }
        public bool IsInited { get; protected set; }
        public bool IsFirstTimeNow { get; protected set; }
        
        public PeriodQuantityLimitter()
        {
            MaxQuantity = -1;
            CurrentQuantity = 0;
            IsStarted = false;
            IsFirstTimeNow = true;
        }

        public void Init(TimeSpan period, int maxQuantity, int reduceFirstTime)
        {
            Period = period;
            MaxQuantity = maxQuantity;
            ReduceFirstTime = reduceFirstTime;
            IsInited = true;
        }

        public void Start()
        {
            if (!IsInited)
                return;

            if (IsStarted)
                return;

            StartMoment = DateTime.Now;
            IsStarted = true;
        }

        public void Stop()
        {
            if (!IsInited)
                return;

            if (!IsStarted)
                return;

            IsStarted = false;
        }

        public void Increment()
        {
            if (!IsInited)
                return;

            if (!IsStarted)
                return;

            DateTime dt = DateTime.Now;
            if (StartMoment.Add(Period) >= dt)
            {
                CurrentQuantity++;
            }
            else
            {
                StartMoment = dt;
                CurrentQuantity = 1;
                IsFirstTimeNow = false;
            }
        }

        public bool IsEnabled()
        {
            if (!IsInited)
                return true;

            if (!IsStarted)
                return true;

            DateTime dt = DateTime.Now;
            if (StartMoment.Add(Period) < dt)
            {
                StartMoment = dt;
                CurrentQuantity = 0;
                IsFirstTimeNow = false;
            }

            if (IsFirstTimeNow)
                return CurrentQuantity < MaxQuantity - ReduceFirstTime;
            else
                return CurrentQuantity < MaxQuantity;
        }
    }
}
